package com.imc.api.templmess.utils;

import com.alibaba.fastjson.JSONObject;
import com.imc.core.annotation.Logs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/*微信模板消息发送类
 * 类描述：
 * 开发者：YT
 * 创建日期：2018/10/23 18:33
 */
public class WX_TemplateMsgUtil {
    private static Logger log = LoggerFactory.getLogger(WX_TemplateMsgUtil.class);

    private static WX_TemplateMsgUtil instance = new WX_TemplateMsgUtil();

    private WX_TemplateMsgUtil() {

    }

    public static WX_TemplateMsgUtil getInstance() {
        return instance;
    }

    /**
     * 封装模板详细信息
     */
    public static JSONObject packJsonmsg(Map <String, TemplateData> param) {
        JSONObject json = new JSONObject();
        for (Map.Entry <String, TemplateData> entry : param.entrySet()) {
            JSONObject keyJson = new JSONObject();
            TemplateData dta = entry.getValue();
            keyJson.put("value", dta.getValue());
            keyJson.put("color", dta.getColor());
            json.put(entry.getKey(), keyJson);
        }
        return json;
    }

    /**
     * 根据模板的编号 新增并获取模板ID
     */
    public static String getWXTemplateMsgId(String templateSerialNumber, String appId, String appSecret) {
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + WXTokenUtil.getWXToken(appId, appSecret).getAccessToken();
        JSONObject json = new JSONObject();
        json.put("template_id_short", templateSerialNumber);
        JSONObject result = WXHttpsUtil.httpsRequest(tmpurl, "POST", json.toString());
        JSONObject resultJson = new JSONObject(result);
        String errmsg = (String) resultJson.get("errmsg");
        log.info("获取模板编号返回信息：" + errmsg);
        if (!"ok".equals(errmsg)) {
            return "error";
        }
        String templateId = (String) resultJson.get("template_id");
        return templateId;
    }

    /**
     * 根据模板ID 删除模板消息
     */
    public static String deleteWXTemplateMsgById(String templateId, String appId, String appSecret) {
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=" + WXTokenUtil.getWXToken(appId, appSecret).getAccessToken();
        JSONObject json = new JSONObject();
        json.put("template_id", templateId);
        try {
            JSONObject result = WXHttpsUtil.httpsRequest(tmpurl, "POST", json.toString());
            JSONObject resultJson = new JSONObject(result);
            log.info("删除" + templateId + "模板消息,返回CODE：" + resultJson.get("errcode"));
            String errmsg = (String) resultJson.get("errmsg");
            if (!"ok".equals(errmsg)) {
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }


    /**
     * 发送微信消息(模板消息)
     */
    public String sendWechatMsgToUser(String page, String formId, String touser, String templatId, String clickurl, String topcolor, JSONObject data, String appId, String appSecret) {
        //String access_token = null;//WXTokenUtil.getWXToken(appId,appSecret).getAccessToken();
        String access_token = WXTokenUtil.getWXToken(appId, appSecret).getAccessToken();
        log.info("access_token : " + access_token);
        //System.out.println(access_token);
        //access_token = "14_5lXwchvACsbYy1PU3Y9gaYJRvIpx4oLRHqS6bKXhkZTFlixLfRO82xMg2NujUR6LH2NR_yZeg5aE8zfquDHvitw1m8XDxCYdeW4H_wLSmixKu7XV9zmgk0gQjNHX2Zl8T5USdMvWIPQVKjkFSOLgAAAJFC";
        String littleProgramUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;
        //String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+ access_token;
        JSONObject json = new JSONObject();
        json.put("touser", touser);
        json.put("template_id", templatId);
        json.put("url", clickurl);
        json.put("topcolor", topcolor);
        json.put("data", data);
        json.put("form_id", formId);
        json.put("page", page);
        log.info("template request params : " + json.toString());
        try {
            JSONObject result = WXHttpsUtil.httpsRequest(littleProgramUrl, "POST", json.toString());
            JSONObject resultJson = new JSONObject(result);
            log.info("resultJson:"+resultJson);
            log.info("发送微信消息返回信息Code：" + resultJson.get("errcode"));
            String errmsg = (String) resultJson.get("errmsg");
            log.info("发送微信消息返回信息MSG：" + errmsg);
            if (!"ok".equals(errmsg)) {  //如果为errmsg为ok，则代表发送成功，公众号推送信息给用户了。
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        } finally {
            if (templatId != null) {
                //删除新增的 微信模板
                //deleteWXTemplateMsgById(templatId, appId, appSecret);
            }
        }
        return "success";
    }
}
